package warmachineroster.service.validation;

import java.util.ArrayList;
import java.util.List;

import warmachineroster.Roster;

public class WarmachineRosterValidationServiceImpl implements
		WarmachineRosterValidationService {


	private List<RosterValidator> validators = new ArrayList<RosterValidator>();

	public static WarmachineRosterValidationService INSTANCE = new WarmachineRosterValidationServiceImpl();

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * warmachineroster.service.validation.WarmachineRosterValidationService
	 * #registerModel(warmachineroster.Roster)
	 */
	@Override
	public void registerModel(Roster roster) {
		RosterValidator validator = new RosterValidator(roster);
		validator.init();
		validators.add(validator);
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * warmachineroster.service.validation.WarmachineRosterValidationService
	 * #unregisterModel(warmachineroster.Roster)
	 */
	@Override
	public void unregisterModel(Roster roster) {
		RosterValidator validator = getRosterValidator(roster);
		validator.dispose();
		validators.remove(validator);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * warmachineroster.service.validation.WarmachineRosterValidationService
	 * #register(warmachineroster.service.validation.ValidationChangeListener)
	 */
	@Override
	public void register(IValidationChangeListener listener, Roster roster) {
		getRosterValidator(roster).addListener(listener);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * warmachineroster.service.validation.WarmachineRosterValidationService
	 * #unregister(warmachineroster.service.validation.ValidationChangeListener)
	 */
	@Override
	public void unregister(IValidationChangeListener listener, Roster roster) {
		getRosterValidator(roster).removeListener(listener);
	}

	private RosterValidator getRosterValidator(Roster roster) {
		for (RosterValidator validator : validators) {
			if (validator.getRoster().equals(roster))
				return validator;
		}
		return null;
	}

}
